<template>
  <div class="app-container">
    <el-card>
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发送对象：" prop="memberType">
              <el-radio v-model="formData.memberType" :label="0">会员</el-radio>
              <el-radio v-model="formData.memberType" :label="1">企业主</el-radio>
            </el-form-item>

            <el-form-item label="群发模板：" prop="smsTemplateId">
              <el-select
                v-model="formData.smsTemplateId"
                placeholder="请选择群发模板"
                @change="templateChange"
                clearable
              >
                <el-option
                  v-for="(item, index) in selectList"
                  :key="index"
                  :label="item.content"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="模板参数：" required>
              <el-row class="mb-15" v-for="(item, index) in selectTemplateList" :key="index">
                <el-col :span="8">
                  <el-input v-model="item.key" placeholder="请选择模板自动填充参数" disabled />
                </el-col>
                <el-col :span="16">
                  <el-radio-group
                    v-model="item.value"
                    @change="changeTemplateRadio($event, index)"
                    class="ml-10"
                  >
                    <el-radio :disabled="!item.key" :label="'$userName$'"> 用户名 </el-radio>
                    <el-radio :disabled="!item.key" :label="'$userPhone$'"> 电话号码 </el-radio>
                    <el-radio :disabled="!item.key" :label="'$content$'"> 自定义 </el-radio>
                  </el-radio-group>
                  <el-button
                    v-if="item.value === '$content$'"
                    class="ml-10"
                    :disabled="!item.key"
                    type="text"
                    @click="openCustomPopup(index)"
                  >
                    自定义变量
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>

            <el-row>
              <el-col :span="14">
                <el-form-item label="发送时间：" prop="sendWay" required>
                  <el-radio-group v-model="formData.sendWay">
                    <el-radio
                      v-for="(item, index) in SHORT_LETTER_TIME_LABEL"
                      @change="sendTimeChange"
                      :key="index"
                      :label="item.value"
                    >
                      {{ item.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item v-if="formData.sendWay === 2" label-width="0" prop="timingSendTime">
                  <el-date-picker
                    v-model="formData.timingSendTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期时间"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button @click="resetForm"> 取消 </el-button>
          <el-button type="primary" @click="submitForm"> 发送 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 自定义弹窗 -->
    <CustomPopup
      v-if="popupVisible"
      :current-index="currIndex"
      :current-content="currentContent"
      :dialog-visible.sync="popupVisible"
      @submit="submitContent"
    />
  </div>
</template>
<script>
import _ from 'lodash'
import CustomPopup from './popup.vue'
import { SHORT_LETTER_TIME_LABEL } from '@/enum/message'
export default {
  components: {
    CustomPopup
  },
  props: [],
  data() {
    return {
      popupVisible: false,
      content: '',
      formData: {
        memberType: '',
        sendWay: 1,
        smsTemplateId: '',
        timingSendTime: ''
      },
      selectList: [],
      rules: {
        memberType: [
          {
            required: true,
            message: '请选择发送对象',
            trigger: 'change'
          }
        ],
        smsTemplateId: [
          {
            required: true,
            message: '请选择群发模板',
            trigger: 'change'
          }
        ],
        timingSendTime: [
          {
            required: true,
            message: '请选择发送时间',
            trigger: 'change'
          }
        ]
      },
      selectTemplateList: [{ key: '', value: '' }],
      paramsList: [],
      currIndex: '',
      currentContent: ''
    }
  },
  computed: {
    // 发送时间
    SHORT_LETTER_TIME_LABEL() {
      return SHORT_LETTER_TIME_LABEL
    }
  },
  created() {
    this.getSelectList()
  },
  methods: {
    async getSelectList() {
      const { data } = await this.$http.message.massApi.selectList()
      this.selectList = data
    },
    // 获取参数
    getParams() {
      // 模板参数类型 $userName$： 用户名 $userPhone$：电话号码 $content$： 自定义
      const data = {
        ...this.formData
      }
      let flag = this.paramsList.every(item => item.key !== '')
      if (flag) {
        data.params = this.paramsList
      } else {
        data.params = []
      }
      return data
    },
    // 选择模板
    templateChange(id) {
      let params = this.selectList.filter(item => item.id === id)[0].paramList.split(',')
      this.selectTemplateList = params.map(item => {
        return {
          key: item,
          value: item ? '$userName$' : ''
        }
      })
      this.paramsList = this.$lodash.cloneDeep(this.selectTemplateList)
    },
    // 选择模板参数
    changeTemplateRadio(value, currIndex) {
      this.selectTemplateList = this.selectTemplateList.map((item, index) => {
        if (currIndex === index) {
          item.value = value
        }
        return item
      })
      this.paramsList = this.$lodash.cloneDeep(this.selectTemplateList).map(item => {
        if (item.value === '$content$') {
          item.value = ''
        }
        return item
      })
    },
    // 提交
    submitForm: _.debounce(async function () {
      this.$refs['elForm'].validate(async valid => {
        if (!valid) return false
        let flag1 = this.paramsList.some(item => item.value === '')
        let flag2 = this.paramsList.some(item => item.key !== '')
        if (!this.content && flag1 && flag2) return this.$message.error('请输入自定变量的值')
        const params = this.getParams()
        const { status, msg } = await this.$http.message.massApi.massTexting(params)
        if (status === 200) {
          this.$message.success('发送成功')
          this.$router.back(-1)
        } else {
          this.$message.error(msg)
        }
      })
    }, 200),
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$router.back(-1)
    },
    // 自定义变量
    openCustomPopup(index) {
      this.currIndex = index
      this.popupVisible = true
      let curAttr = this.paramsList.filter((item, cIndex) => index === cIndex)
      this.currentContent = curAttr.length ? curAttr[0].value : ''
    },
    // 自定义参数提交
    submitContent({ index, content }) {
      this.paramsList = this.paramsList.map((item, cIndex) => {
        if (index === cIndex) {
          item.value = content
        }
        return item
      })
    },
    // 发送时间
    sendTimeChange() {
      this.formData.timingSendTime = ''
    }
  }
}
</script>
